const knex = require('./conn');

async function getPageByPath({path}) {
  const pageSpec = await knex('page-spec');

  let pathSegs = path.replace(/^\/+|\/+$/, '').split('/');
    
  console.log(pathSegs);

  let list = Object.fromEntries(pageSpec.map(({key, ...rest}) => [key, rest]));
  let page;

  for (let i = 0; i < pathSegs.length; i++) {
    page = list[pathSegs[i]];
    if (!page) {
      break;
    } else if (!page['link-to']) {
      break;
    } else {
      list = Object.fromEntries(page['link-to'].map(name => [name, list[name]]))
    }
  }

  return page ?? pageSpec.find(({key}) => key === '404');
}

module.exports = {
  getPageByPath
};